﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;

namespace SPContrib.SharePoint.Extensions
{
    /// <summary>
    /// Extensions for the SPContentTypeCollection class
    /// </summary>
    public static class SPContentTypeCollectionExtensions
    {
        /// <summary>
        /// Query the collection for SPContentTypes that meets the search criteria
        /// </summary>
        /// <param name="criteria">the search criteria delegate (e.g. ctype => ctype.Name == "SomeContentType")</param>
        /// <remarks>Don´t use this method to search by id, use TryFindById instead</remarks>
        public static IEnumerable<SPContentType> FindByCriteria(this SPContentTypeCollection instance, Predicate<SPContentType> criteria)
        { 
            //TODO: can we check for id and use the other method then...?

            return from SPContentType ctype in instance
                   where criteria(ctype)
                   select ctype;
        }

        /// <summary>
        /// Query the collection for a SPContentType that meets the id criteria. 
        /// A boolean indicates if the query was successful or not.
        /// </summary>
        /// <param name="id">the id of the SPContentType</param>
        /// <param name="result">the SPContentType to return if the query is successful</param>
        public static bool TryFindById(this SPContentTypeCollection instance, SPContentTypeId id, out SPContentType result)
        {
            SPContentTypeId bestmatch = instance.BestMatch(id);

            if (bestmatch.IsChildOf(id) == false && bestmatch.Equals(id) == false)
            {
                result = default(SPContentType);
                return false;
            }

            result = instance[bestmatch];
            return true;
        }
    }
}
